package com.mixpanel.example.hello.activity;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.mixpanel.android.mpmetrics.MixpanelAPI;
import com.mixpanel.android.mpmetrics.OnMixpanelUpdatesReceivedListener;
import com.mixpanel.android.util.L;
import com.mixpanel.example.hello.App;
import com.mixpanel.example.hello.R;
import com.mixpanel.example.hello.pupupwindow.GravityActivity;
import com.mixpanel.example.hello.pupupwindow.PopupActivity;
import com.mixpanel.example.hello.pupupwindow.listview.ListViewActivity;
import com.mixpanel.example.hello.visual.NestingActivity;
import com.mixpanel.example.hello.visual.VisualMainActivity;
import com.mixpanel.example.hello.visual.WebViewActivity;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 主界面
 */
public class MainActivity extends Activity {

    private static final String MIXPANEL_DISTINCT_ID_NAME = "Mixpanel Example $distinctid";
    private static final int PHOTO_WAS_PICKED = 2;
    private static final String LOGTAG = "sanbo";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mixpanelOnCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    MixpanelAPI.getInstance(MainActivity.this, App.MIXPANEL_API_TOKEN).track("MainActivity..." + System.currentTimeMillis());
                }
            }
        }).start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mixpanelOnResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        App.mMixpanel.flush();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (PHOTO_WAS_PICKED == requestCode && null != data) {
            final Uri imageUri = data.getData();
            if (null != imageUri) {
                // AsyncTask, please...
                final ContentResolver contentResolver = getContentResolver();
                try {
                    final InputStream imageStream = contentResolver.openInputStream(imageUri);
                    System.out.println("DRAWING IMAGE FROM URI " + imageUri);
                    final Bitmap background = BitmapFactory.decodeStream(imageStream);
                    getWindow().setBackgroundDrawable(new BitmapDrawable(getResources(), background));
                } catch (final FileNotFoundException e) {
                    Log.e(LOGTAG, "Image apparently has gone away", e);
                }
            }
        }
    }

    private void mixpanelOnCreate() {
        final String trackingDistinctId = getTrackingDistinctId();
        App.mMixpanel.identify(trackingDistinctId); //this is the distinct_id value that
        App.mMixpanel.getPeople().identify(trackingDistinctId); //this is the distinct_id
    }

    private void mixpanelOnResume() {
        final long nowInHours = hoursSinceEpoch();
        final int hourOfTheDay = hourOfTheDay();

        try {
            final JSONObject properties = new JSONObject();
            properties.put("first viewed on", nowInHours);
            properties.put("user domain", "(unknown)"); // default value
            App.mMixpanel.registerSuperPropertiesOnce(properties);
        } catch (final JSONException e) {
            throw new RuntimeException("Could not encode hour first viewed as JSON");
        }

        try {
            final JSONObject properties = new JSONObject();
            properties.put("hour of the day", hourOfTheDay);
            App.mMixpanel.track("App Resumed", properties);
        } catch (final JSONException e) {
            throw new RuntimeException("Could not encode hour of the day in JSON");
        }

        App.mMixpanel.getPeople().showNotificationIfAvailable(this);
        OnMixpanelUpdatesReceivedListener listener = new OnMixpanelUpdatesReceivedListener() {
            @Override
            public void onMixpanelUpdatesReceived() {
                App.mMixpanel.getPeople().joinExperimentIfAvailable();
            }
        };
        App.mMixpanel.getPeople().addOnMixpanelUpdatesReceivedListener(listener);
    }

    public void dialog(final View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确认退出吗？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                MainActivity.this.finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    public void pupupWindow(final View view) {
        startActivity(new Intent(this, PopupActivity.class));
    }

    public void btnListView(final View view) {
        startActivity(new Intent(this, ListViewActivity.class));
    }

    public void textView(final View view) {
        TextView tv = (TextView) this.findViewById(R.id.textView);
        tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                L.d("你点击了textview");
            }
        });
    }

    public void buttonVis(final View view) {
        startActivity(new Intent(this, VisualMainActivity.class));
    }

    public void customPupupWindow(final View view) {
        startActivity(new Intent(this, GravityActivity.class));
    }

    public void sendToMixpanel(final View view) {

        final TextView firstNameEdit = (TextView) findViewById(R.id.textview_first_name);
        final EditText lastNameEdit = (EditText) findViewById(R.id.edittext_last_name);
        final EditText emailEdit = (EditText) findViewById(R.id.edittext_email_address);

        final String firstName = firstNameEdit.getText().toString();
        final String lastName = lastNameEdit.getText().toString();
        final String email = emailEdit.getText().toString();

        final MixpanelAPI.People people = App.mMixpanel.getPeople();

        people.set("$first_name", firstName);
        people.set("$last_name", lastName);
        people.set("$email", email);
        people.increment("Update Count", 1L);

        try {
            final JSONObject domainProperty = new JSONObject();
            domainProperty.put("user domain", domainFromEmailAddress(email));
            App.mMixpanel.registerSuperProperties(domainProperty);
        } catch (final JSONException e) {
            throw new RuntimeException("Cannot write user email address domain as a super property");
        }
        App.mMixpanel.track("update info button clicked", null);
    }

    // This is an example of how you can use Mixpanel's revenue tracking features from Android.
    public void recordRevenue(final View view) {
        final MixpanelAPI.People people = App.mMixpanel.getPeople();
        people.trackCharge(1.50, null);
    }

    public void goB(final View view) {
        startActivity(new Intent(this, B.class));
    }

    public void btnTestAct(final View view) {
        startActivity(new Intent(this, Test.class));
    }

    public void setBackgroundImage(final View view) {
        final Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, PHOTO_WAS_PICKED);
    }

    private String getTrackingDistinctId() {
        final SharedPreferences prefs = getPreferences(MODE_PRIVATE);

        String ret = prefs.getString(MIXPANEL_DISTINCT_ID_NAME, null);
        if (ret == null) {
            ret = generateDistinctId();
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            prefsEditor.putString(MIXPANEL_DISTINCT_ID_NAME, ret);
            prefsEditor.commit();
        }

        return ret;
    }

    private String generateDistinctId() {
        final Random random = new Random();
        final byte[] randomBytes = new byte[32];
        random.nextBytes(randomBytes);
        return Base64.encodeToString(randomBytes, Base64.NO_WRAP | Base64.NO_PADDING);
    }

    private int hourOfTheDay() {
        final Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    private long hoursSinceEpoch() {
        final Date now = new Date();
        final long nowMillis = now.getTime();
        return nowMillis / 1000 * 60 * 60;
    }

    private String domainFromEmailAddress(String email) {
        String ret = "";
        final int atSymbolIndex = email.indexOf('@');
        if ((atSymbolIndex > -1) && (email.length() > atSymbolIndex)) {
            ret = email.substring(atSymbolIndex + 1);
        }

        return ret;
    }

    public void nestingBtn(final View view) {
        Intent intent = new Intent(this, NestingActivity.class);
        startActivity(intent);
    }

    public void webBtn(final View view) {
        Intent intent = new Intent(this, WebViewActivity.class);
        startActivity(intent);
    }

    public void onClick(final View view) {
        startActivity(new Intent(this, IndexActivity.class));
    }
}
